 

package c.x.jy.api.interceptor;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;

import c.x.jy.common.annotation.Login;
import c.x.jy.common.exception.RRException;
import c.x.jy.dao.entity.BusinessEntity;
import c.x.jy.dao.entity.MemberEntity;
import c.x.jy.service.entity.form.CommRequest;
import c.x.jy.service.service.BusinessService;
import c.x.jy.service.service.MemberService;
import c.x.jy.service.utils.MemberUtil;
/**
 * 权限(Token)验证
 *
 */ 
@Component
public class  AuthorizationInterceptor1 extends org.springframework.web.servlet.handler.HandlerInterceptorAdapter {
 
	   @Autowired 
	   private MemberService memberService;
	   
	   @Autowired
		private	BusinessService businessService;
	 

    public static final String USER_KEY = "openId";
    public static final String BUSINESS_KEY = "businessCode";
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Login annotation;
        if(handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(Login.class);
        }else{
            return true;
        }

        if(annotation == null){
            return true;
        }

        //获取用户凭证
        String openid = request.getHeader(USER_KEY);
        String businessCode = request.getHeader(BUSINESS_KEY);
        
        if(StringUtils.isBlank(openid) ){
            openid = request.getParameter(USER_KEY);
        }
        if(StringUtils.isBlank(businessCode) ){
        	businessCode = request.getParameter(BUSINESS_KEY);
        }
     
        //凭证为空
        if(StringUtils.isBlank(openid)||StringUtils.isBlank(businessCode)){
            throw new RRException(USER_KEY + "和  " +BUSINESS_KEY + "不能为空", 1);
        }
        
       MemberEntity member=      memberService.getMemberByOpenId(openid);
      BusinessEntity b=  businessService.selectBusinessByCode(businessCode);
        if(member==null) {
      	  throw new RRException("未注册!", 2);
       }
        if(b==null) {
        	  throw new RRException("商家不存在!", 1);
         }
        MemberUtil.set(new CommRequest(openid,businessCode));
        
        return true;
    }
    
 
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
			@Nullable Exception ex) throws Exception {
		System.out.println("remove Token...");
		MemberUtil.remove();
	}
}
